package com.buanalintas.sandals.pos.distribution;

import com.buanalintas.bynga.Access;
import com.buanalintas.bynga.Action;
import com.buanalintas.bynga.Controller;
import com.buanalintas.bynga.Dictionary;
import com.buanalintas.bynga.Field;
import com.buanalintas.bynga.Logger;
import com.buanalintas.bynga.Page;
import com.buanalintas.bynga.Persistence;
import com.buanalintas.bynga.Sequence;
import com.buanalintas.bynga.Template;
import com.buanalintas.bynga.Utility;
import com.buanalintas.bynga.entities.MasterUnit;
import com.buanalintas.bynga.entities.MasterUser;
import com.buanalintas.bynga.formatter.DateFormatter;
import com.buanalintas.bynga.formatter.MoneyFormatter;
import com.buanalintas.sandals.pos.distributiondetail.DistributionDetail;
import com.buanalintas.sandals.pos.entities.PosMasterItemStock;
import com.buanalintas.sandals.pos.entities.PosMasterStatus;
import com.buanalintas.sandals.pos.entities.PosTransactionDistribution;
import com.buanalintas.sandals.pos.entities.PosTransactionDistributionDetail;
import com.buanalintas.sandals.pos.entities.PosTransactionItemStock;
import com.buanalintas.sandals.pos.item.Item;
import com.buanalintas.sandals.pos.status.Status;
import java.math.BigDecimal;
import java.util.Calendar;
import java.util.List;
import javax.persistence.EntityManager;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

public class Distribution extends Page {

    private Field distributionId;
    private Field distributionUserId;
    private Field distributionUnitId;
    private Field distributionDestinationUnitId;
    private Field distributionNumber;
    private Field distributionDate;
    private Field distributionTotal;
    private Field distributionPaid;
    private Field distributionKeel;
    private Field distributionProgress;
    private Field distributionRejectReason;
    private Field distributionStatusId;
    private Field distributionDescription;
    private Field distributionTimestamp;
    private Action actionRevision = new Action("revisi", "Revision Request");
    private Action actionReject = new Action("reject", "Reject Request");
    private Action actionAgree = new Action("approve", "Agree Request");

    public Distribution() {
        super();
        setTheClass(PosTransactionDistribution.class);
        setPageDetail(DistributionDetail.class);

        distributionId = new Field();
        distributionId.setName("distributionId");
        distributionId.setCaption("id");
        distributionId.setListProperties("");
        distributionId.setInputProperties("");
        getFields().add(distributionId);

        distributionUserId = new Field();
        distributionUserId.setName("distributionUserId");
        distributionUserId.setCaption("sender user");
        distributionUserId.setListProperties(" width=\"12%\"");
        distributionUserId.setInputProperties(" size=\"15\"");
        getFields().add(distributionUserId);

        distributionUnitId = new Field();
        distributionUnitId.setName("distributionUnitId");
        distributionUnitId.setCaption("sender unit");
        distributionUnitId.setListProperties(" width=\"12%\"");
        distributionUnitId.setInputProperties(" size=\"15\"");
        getFields().add(distributionUnitId);

        distributionDestinationUnitId = new Field();
        distributionDestinationUnitId.setName("distributionDestinationUnitId");
        distributionDestinationUnitId.setCaption("destination unit");
        distributionDestinationUnitId.setListProperties(" width=\"20%\"");
        distributionDestinationUnitId.setInputProperties(" size=\"15\" readonly");
        distributionDestinationUnitId.setRequired(true);
        distributionDestinationUnitId.getSelectorColumns().add(new String[]{"unitName", " Name", "width=\"30%\" nowrap"});
        distributionDestinationUnitId.getSelectorColumns().add(new String[]{"unitDescription", " Description", "width=\"70%\""});
        distributionDestinationUnitId.getViewColumns().addAll(distributionDestinationUnitId.getSelectorColumns());
        getFields().add(distributionDestinationUnitId);

        distributionNumber = new Field();
        distributionNumber.setName("distributionNumber");
        distributionNumber.setCaption("number");
        distributionNumber.setListProperties(" align=\"center\" width=\"15%\" nowrap");
        distributionNumber.setInputProperties(" size=\"20\" readonly");
        distributionNumber.setRequired(true);
        getFields().add(distributionNumber);

        distributionDate = new Field();
        distributionDate.setName("distributionDate");
        distributionDate.setCaption("date");
        distributionDate.setListProperties(" align=\"center\" width=\"10%\" nowrap");
        distributionDate.setInputProperties(" size=\"8\"");
        distributionDate.setDefaultValue(Utility.getTimestamp());
        getFields().add(distributionDate);
        
        distributionTotal = new Field();
        distributionTotal.setName("distributionTotal");
        distributionTotal.setCaption("total");
        distributionTotal.setListProperties(" align=\"right\" width=\"8%\" nowrap");
        distributionTotal.setInputProperties(" size=\"8\"");
//        distributionTotal.setRequired(true);
        distributionTotal.setFormater(MoneyFormatter.getInstance());
        getFields().add(distributionTotal);

        distributionPaid = new Field();
        distributionPaid.setName("distributionPaid");
        distributionPaid.setCaption("paid");
        distributionPaid.setListProperties(" align=\"right\" width=\"8%\" nowrap");
        distributionPaid.setInputProperties(" size=\"8\"");
//        distributionPaid.setRequired(true);
        distributionPaid.setFormater(MoneyFormatter.getInstance());
        getFields().add(distributionPaid);
        
        distributionKeel = new Field();
        distributionKeel.setName("distributionKeel");
        distributionKeel.setCaption("keel");
        distributionKeel.setListProperties(" align=\"center\" width=\"5%\" nowrap");
        distributionKeel.setInputProperties(" ");
        distributionKeel.getOptions().add(new String[]{"1", "NO"});
        distributionKeel.getOptions().add(new String[]{"2", "YES"});
        getFields().add(distributionKeel);

        distributionProgress = new Field();
        distributionProgress.setName("distributionProgress");
        distributionProgress.setCaption("progress");
        distributionProgress.setListProperties(" align=\"center\" width=\"5%\" nowrap");
        distributionProgress.setInputProperties("");
        distributionProgress.setInputType(Field.INPUT_COMBO_BOX);
        distributionProgress.getOptions().add(new String[]{"1", "New"});
        distributionProgress.getOptions().add(new String[]{"2", "Revision"});
        distributionProgress.getOptions().add(new String[]{"3", "Rejected"});
        distributionProgress.getOptions().add(new String[]{"4", "Approved"});
        distributionProgress.getOptions().add(new String[]{"5", "New"});
        getFields().add(distributionProgress);

        distributionRejectReason = new Field();
        distributionRejectReason.setName("distributionRejectReason");
        distributionRejectReason.setCaption("reason");
        distributionRejectReason.setListProperties(" width=\"10%\" nowrap");
        distributionRejectReason.setInputProperties("");
        distributionRejectReason.setInputCase(Field.CASE_UPPER);
        getFields().add(distributionRejectReason);

        distributionStatusId = new Field();
        distributionStatusId.setName("distributionStatusId");
        distributionStatusId.setCaption("status");
        distributionStatusId.setListProperties(" align=\"center\" width=\"5%\" nowrap");
        distributionStatusId.setInputType(Field.INPUT_COMBO_BOX);
        distributionStatusId.setInputProperties("");
        getFields().add(distributionStatusId);

        distributionDescription = new Field();
        distributionDescription.setName("distributionDescription");
        distributionDescription.setCaption("description");
        distributionDescription.setListProperties(" width=\"35%\"");
        distributionDescription.setInputProperties(" cols=\"50\" rows=\"5\"");
        distributionDescription.setInputType(Field.INPUT_TEXT_AREA);
        distributionDescription.setInputCase(Field.CASE_UPPER);
        getFields().add(distributionDescription);

        distributionTimestamp = new Field();
        distributionTimestamp.setName("distributionTimestamp");
        distributionTimestamp.setCaption("timestamp");
        distributionTimestamp.setListProperties(" align=\"center\" width=\"5%\" nowrap");
        distributionTimestamp.setInputProperties(" size=\"8\"");
        getFields().add(distributionTimestamp);

        getActions().add(Action.TRANS_ADD);
        getActions().add(Action.TRANS_EDIT);
        getActions().add(Action.TRANS_VIEW);
        
        fillFields();

        getFieldsAdd().clear();
        getFieldsAdd().add(distributionNumber);
        getFieldsAdd().add(distributionDate);
        getFieldsAdd().add(distributionDestinationUnitId);
//        getFieldsAdd().add(distributionTotal);
//        getFieldsAdd().add(distributionPaid);
        getFieldsAdd().add(distributionStatusId);
        getFieldsAdd().add(distributionDescription);

        getFieldsEdit().clear();
        getFieldsEdit().add(distributionNumber);
        getFieldsEdit().add(distributionDate);
        getFieldsEdit().add(distributionDestinationUnitId);
//        getFieldsEdit().add(distributionTotal);
//        getFieldsEdit().add(distributionPaid);
        getFieldsEdit().add(distributionStatusId);
        getFieldsEdit().add(distributionDescription);

        getFieldsList().clear();
        getFieldsList().add(distributionNumber);
        getFieldsList().add(distributionDate);
        getFieldsList().add(distributionDestinationUnitId);
        getFieldsList().add(distributionTotal);
        getFieldsList().add(distributionPaid);
        getFieldsList().add(distributionKeel);
        getFieldsList().add(distributionStatusId);
        getFieldsList().add(distributionRejectReason);
        getFieldsList().add(distributionDescription);
        getFieldsList().add(distributionProgress);

        getFieldsView().clear();
        getFieldsView().add(distributionDate);
        getFieldsView().add(distributionNumber);
        getFieldsView().add(distributionUserId);
        getFieldsView().add(distributionUnitId);
        getFieldsView().add(distributionDestinationUnitId);
        getFieldsView().add(distributionTotal);
        getFieldsView().add(distributionPaid);
        getFieldsView().add(distributionKeel);
        getFieldsView().add(distributionDescription);
        getFieldsView().add(distributionStatusId);
        getFieldsView().add(distributionTimestamp);

        setController(new DistributionController(this));
        setExportList(getClass().getResourceAsStream("DistributionList.jasper"));
        setExport(getClass().getResourceAsStream("Distribution.jasper"));

        setController(new DistributionController(this));
        getActions().add(actionRevision);
        getActions().add(actionAgree);
        getActions().add(actionReject);
    }

    @Override
    public void afterInit(HttpServletRequest req, HttpServletResponse res) {
        distributionDate.setFormater(DateFormatter.getInstanceDate(this));
        distributionTimestamp.setFormater(DateFormatter.getInstanceDateTime(this));
    }

    @Override
    public void beforeAdd() {
        distributionNumber.setDefaultValue(generate());
    }

    @Override
    public void beforeList() {
        if (!getCurrentUnit().getUnitId().equals(1)) {
            getController().setCondition("t.distributionDestinationUnitId.unitId=" + getCurrentUnit().getUnitId());
        }
    }
    
    public static MasterUnit getUnit(EntityManager em) {
        try {
            javax.persistence.Query query = em.createQuery("SELECT t FROM MasterUnit t WHERE t.unitId=1");
            return (MasterUnit) query.getSingleResult();
        } catch (Exception e) {
        }
        return null;
    }

    @Override
    public String addJavascript() {
        return "<script>function __reject(id) {var reason = prompt('" + Dictionary.getValue(this, "Enter rejected reason") + "?', ''); if (reason != null) { location.href = \"?m=" + getMenu().getMenuName() + "&a=" + actionReject.getName() + "&id=\"+id+\"&reason=\"+escape(reason); } return false; }</script>";
    }

    @Override
    public boolean isGranted(Action action, Object data) {
        boolean granted = super.isGranted(action, data);
        if (granted) {
            PosTransactionDistribution distribution = (PosTransactionDistribution) data;
            if (action.equals(Action.EDIT) || action.equals(Action.TRANS_EDIT) || action.equals(Action.DELETE)) {
                granted = distribution.getDistributionProgress() == null || distribution.getDistributionProgress().equals("1") || distribution.getDistributionProgress().equals("2");
            }
        }
        return granted;
    }

    @Override
    public String delete(Object data) {
        String delete = super.delete(data);
        if (delete == null) {
            PosTransactionDistribution distribution = (PosTransactionDistribution) data;
            if (!"1".equals(distribution.getDistributionProgress())||!"5".equals(distribution.getDistributionProgress())) {
                delete = Dictionary.getValue(this, "can not be deleted");
            }
        }
        return delete;
    }

    @Override
    public StringBuffer processCustomRowCommand(StringBuffer template, Page page, Object data) {
        StringBuffer commands = new StringBuffer();
        StringBuffer command = null;
        PosTransactionDistribution distribution = (PosTransactionDistribution) data;
        if (distribution.getDistributionProgress() == null || distribution.getDistributionProgress().equals("1")|| distribution.getDistributionProgress().equals("5")) {
            if (Access.isGranted(page, actionRevision)) {
                command = new StringBuffer(template.toString());
                Utility.replaceAll(command, Template.TABLE_ROW_MENU_COMMAND_CUSTOM_LINK, "?m=" + page.getMenu().getMenuName() + "&a=" + actionRevision.getName() + "&id=" + Utility.encode(Utility.getStringValue(data, page.getPrimaryKeyField())));
                Utility.replaceAll(command, Template.TABLE_ROW_MENU_COMMAND_CUSTOM_TITLE, Dictionary.getValue(page, "Revision request"));
                Utility.replaceAll(command, Template.TABLE_ROW_MENU_COMMAND_CUSTOM_PROPERTIES, " onclick=\"return __revision('" + Utility.encode(Utility.getStringValue(data, page.getPrimaryKeyField())) + "')\"");
                Utility.replaceAll(command, Template.TABLE_ROW_MENU_COMMAND_CUSTOM_IMAGE, "?image=command-revision.png");
                commands.append(command.toString());
            }
            if (Access.isGranted(page, actionReject)) {
                command = new StringBuffer(template.toString());
                Utility.replaceAll(command, Template.TABLE_ROW_MENU_COMMAND_CUSTOM_LINK, "?m=" + page.getMenu().getMenuName() + "&a=" + actionReject.getName() + "&id=" + Utility.encode(Utility.getStringValue(data, page.getPrimaryKeyField())));
                Utility.replaceAll(command, Template.TABLE_ROW_MENU_COMMAND_CUSTOM_TITLE, Dictionary.getValue(page, "Reject request"));
                Utility.replaceAll(command, Template.TABLE_ROW_MENU_COMMAND_CUSTOM_PROPERTIES, " onclick=\"return __reject('" + Utility.encode(Utility.getStringValue(data, page.getPrimaryKeyField())) + "')\"");
                Utility.replaceAll(command, Template.TABLE_ROW_MENU_COMMAND_CUSTOM_IMAGE, "?image=command-reject.png");
                commands.append(command.toString());
            }
            if (Access.isGranted(page, actionAgree)) {
                command = new StringBuffer(template.toString());
                Utility.replaceAll(command, Template.TABLE_ROW_MENU_COMMAND_CUSTOM_LINK, "?m=" + page.getMenu().getMenuName() + "&a=" + actionAgree.getName() + "&id=" + Utility.encode(Utility.getStringValue(data, page.getPrimaryKeyField())));
                Utility.replaceAll(command, Template.TABLE_ROW_MENU_COMMAND_CUSTOM_TITLE, Dictionary.getValue(page, "Approve request"));
                Utility.replaceAll(command, Template.TABLE_ROW_MENU_COMMAND_CUSTOM_PROPERTIES, " onclick=\"return confirm('" + Dictionary.getValue(page, "Approve request") + "?')\"");
                Utility.replaceAll(command, Template.TABLE_ROW_MENU_COMMAND_CUSTOM_IMAGE, "?image=command-approve.png");
                commands.append(command.toString());
            }
        }
        return commands;
    }

    @Override
    public String doAction() {

        String id = Utility.decode(Utility.getParameter(getRequest(), "id"));
        if (id != null && !id.trim().equals("")) {
            PosTransactionDistribution data = (PosTransactionDistribution) getController().getData(id);
            if (getAction().equals(actionRevision)) {
                String reason = Utility.getParameter(getRequest(), "reason");
                if (reason == null || reason.trim().equals("")) {
                    return "err:" + Dictionary.getValue(this, "Please enter revision reason");
                }
                try {
                    data.setDistributionProgress("2");
                    data.setDistributionRejectReason(Utility.getParameter(getRequest(), "reason"));
                    getController().update(data);
                    return "ok:" + Dictionary.getValue(this, "Data with") + " " + getObjectInfo(data) + " " + Dictionary.getValue(this, "rejected succesfully");
                } catch (Exception e) {
                    Logger.getInstance().log(e);
                    return "err:" + Dictionary.getValue(this, "Data with") + " " + getObjectInfo(data) + " " + Dictionary.getValue(this, "rejected failed") + ": " + e.getMessage();
                }
            } else if (getAction().equals(actionReject)) {
                String reason = Utility.getParameter(getRequest(), "reason");
                if (reason == null || reason.trim().equals("")) {
                    return "err:" + Dictionary.getValue(this, "Please enter rejected reason");
                }
                try {
                    data.setDistributionProgress("3");
                    data.setDistributionProgress(Utility.getParameter(getRequest(), "reason"));
                    getController().update(data);
                    return "ok:" + Dictionary.getValue(this, "Data with") + " " + getObjectInfo(data) + " " + Dictionary.getValue(this, "rejected succesfully");
                } catch (Exception e) {
                    Logger.getInstance().log(e);
                    return "err:" + Dictionary.getValue(this, "Data with") + " " + getObjectInfo(data) + " " + Dictionary.getValue(this, "rejected failed") + ": " + e.getMessage();
                }
            } else if (getAction().equals(actionAgree)) {
                EntityManager em = getEntityManager();
                PosMasterStatus statusGood = Status.getStatusGood(em);
                try {
                    em.getTransaction().begin();
                    BigDecimal total = BigDecimal.ZERO;
                    
                    PosTransactionDistribution distribution = (PosTransactionDistribution) data;
                    List<PosTransactionDistributionDetail> details = em.createQuery("SELECT t FROM PosTransactionDistributionDetail t WHERE t.distributionDetailDistributionId.distributionId='" + id + "'").setHint(Persistence.REFRESH_HINT, true).getResultList();
                    
                    if ("5".equals(distribution.getDistributionProgress())) {
                        for (PosTransactionDistributionDetail detail : details) {
                            PosMasterItemStock stockUnit = Item.getStock(em, detail.getDistributionDetailItemId(), distribution.getDistributionDestinationUnitId(), statusGood, detail.getDistributionDetailItemId().getItemColorId(), detail.getDistributionDetailSizeId());
                            
                            PosTransactionItemStock itemStock = new PosTransactionItemStock();
                            Integer destinationStock = stockUnit.getItemStockValue() + detail.getDistributionDetailQuantity();

                            itemStock.setItemStockId(Sequence.next(itemStock));
                            itemStock.setItemStockItemId(detail.getDistributionDetailItemId());
                            itemStock.setItemStockSizeId(detail.getDistributionDetailSizeId());
                            itemStock.setItemStockUnitId(distribution.getDistributionDestinationUnitId());
                            itemStock.setItemStockColorId(detail.getDistributionDetailItemId().getItemColorId());
                            itemStock.setItemStockStatusId(statusGood);
                            itemStock.setItemStockType("9");
                            itemStock.setItemStockLast(stockUnit.getItemStockValue());
                            itemStock.setItemStockValue(detail.getDistributionDetailQuantity());
                            itemStock.setItemStockCurrent(stockUnit.getItemStockValue() + itemStock.getItemStockValue());
                            itemStock.setItemStockUserId(distribution.getDistributionUserId());
                            itemStock.setItemStockTimestamp(Utility.getTimestamp());
                            em.persist(itemStock);
                            
                            BigDecimal priceOld = stockUnit.getItemStockItemId().getItemPriceBasic().multiply(new BigDecimal(itemStock.getItemStockValue()));
                            total = stockUnit.getItemStockItemId().getItemPriceShop().multiply(new BigDecimal(detail.getDistributionDetailQuantity()));
                          stockUnit.setItemStockValue(destinationStock);
                        }
                        
                        distribution.setDistributionTotal(total);
                        distribution.setDistributionPaid(BigDecimal.ZERO);
                        distribution.setDistributionKeel("1");
                        distribution.setDistributionProgress("4");
                        em.getTransaction().commit();

                    } else  {
                        for (PosTransactionDistributionDetail detail : details) {
                            PosMasterItemStock stockInventory = Item.getStock(em, detail.getDistributionDetailItemId(), getUnit(em), statusGood, detail.getDistributionDetailItemId().getItemColorId(), detail.getDistributionDetailSizeId());
                            PosMasterItemStock stockUnit = Item.getStock(em, detail.getDistributionDetailItemId(), distribution.getDistributionDestinationUnitId(), statusGood, detail.getDistributionDetailItemId().getItemColorId(), detail.getDistributionDetailSizeId());
                            
                            PosTransactionItemStock itemStocks = new PosTransactionItemStock();
                            PosTransactionItemStock itemStock = new PosTransactionItemStock();

                            Integer senderStock = stockInventory.getItemStockValue() - detail.getDistributionDetailQuantity();
                            Integer destinationStock = stockUnit.getItemStockValue() + detail.getDistributionDetailQuantity();
                            
                            itemStocks.setItemStockId(Sequence.next(itemStock));
                            itemStocks.setItemStockItemId(detail.getDistributionDetailItemId());
                            itemStocks.setItemStockSizeId(detail.getDistributionDetailSizeId());
                            itemStocks.setItemStockColorId(detail.getDistributionDetailItemId().getItemColorId());
                            itemStocks.setItemStockUnitId(getUnit(em));
                            itemStocks.setItemStockStatusId(statusGood);
                            itemStocks.setItemStockType("3");
                            itemStocks.setItemStockLast(stockInventory.getItemStockValue());
                            itemStocks.setItemStockValue(detail.getDistributionDetailQuantity());
                            itemStocks.setItemStockCurrent(stockInventory.getItemStockValue() - itemStocks.getItemStockValue());
                            itemStocks.setItemStockUserId(distribution.getDistributionUserId());
                            itemStocks.setItemStockTimestamp(Utility.getTimestamp());
                            em.persist(itemStocks);
                            
                            itemStock.setItemStockId(Sequence.next(itemStock));
                            itemStock.setItemStockItemId(detail.getDistributionDetailItemId());
                            itemStock.setItemStockUnitId(distribution.getDistributionDestinationUnitId());
                            itemStock.setItemStockSizeId(detail.getDistributionDetailSizeId());
                            itemStock.setItemStockColorId(detail.getDistributionDetailItemId().getItemColorId());
                            itemStock.setItemStockStatusId(statusGood);
                            itemStock.setItemStockType("3");
                            itemStock.setItemStockLast(stockUnit.getItemStockValue());
                            itemStock.setItemStockValue(detail.getDistributionDetailQuantity());
                            itemStock.setItemStockCurrent(stockUnit.getItemStockValue() + itemStock.getItemStockValue());
                            itemStock.setItemStockUserId(getCurrentUser());
                            itemStock.setItemStockTimestamp(Utility.getTimestamp());
                            em.persist(itemStock);
                            
//                            itemStocks.setItemStockId(Sequence.next(itemStock));
//                            itemStocks.setItemStockItemId(detail.getDistributionDetailItemId());
//                            itemStocks.setItemStockSizeId(detail.getDistributionDetailSizeId());
//                            itemStocks.setItemStockUnitId(getUnit(em));
//                            itemStocks.setItemStockStatusId(statusGood);
//                            itemStocks.setItemStockType("3");
//                            itemStocks.setItemStockLast(stockInventory.getItemStockValue());
//                            itemStocks.setItemStockValue(detail.getDistributionDetailQuantity());
//                            itemStocks.setItemStockCurrent(stockInventory.getItemStockValue() - itemStocks.getItemStockValue());
//                            itemStocks.setItemStockUserId(distribution.getDistributionUserId());
//                            itemStocks.setItemStockTimestamp(Utility.getTimestamp());
//                            em.persist(itemStocks);

//                            BigDecimal priceOld = stockUnit.getItemStockItemId().getItemPriceBasic().multiply(new BigDecimal(itemStock.getItemStockValue()));
                            total = stockUnit.getItemStockItemId().getItemPriceShop().multiply(new BigDecimal(detail.getDistributionDetailQuantity()));

                            stockInventory.setItemStockValue(senderStock);
                            stockUnit.setItemStockValue(destinationStock);
                        }
                        distribution.setDistributionTotal(total);
                        distribution.setDistributionPaid(BigDecimal.ZERO);
                        distribution.setDistributionProgress("4");
                        em.getTransaction().commit();
                    }
                    
                    
                } catch (Exception e) {
                    Logger.getInstance().log(e);
                    return "err:" + Dictionary.getValue(this, "Data with") + " " + getObjectInfo(data) + " " + Dictionary.getValue(this, "approved failed") + ": " + e.getMessage();
                }
            }
        }
        return null;
    }

    class DistributionController extends Controller {

        public DistributionController(Page page) {
            super(page);
            setOrder(distributionTimestamp);
            setOrderType("DESC");
        }

        @Override
        public void beforeInsert(Object data, List detail) {
            PosTransactionDistribution distribution = (PosTransactionDistribution) data;
            distribution.setDistributionNumber(generate());
            distribution.setDistributionUnitId(getCurrentUnit());
            distribution.setDistributionUserId(getCurrentUser());
            distribution.setDistributionKeel("1");
            distribution.setDistributionProgress("1");
            distribution.setDistributionTotal(BigDecimal.ZERO);
            distribution.setDistributionPaid(BigDecimal.ZERO);
            distribution.setDistributionTimestamp(Utility.getTimestamp());
            
//            for (int i = detail.size() - 1; i > 0; i--) {
//                PosTransactionDistributionDetail d1 = (PosTransactionDistributionDetail) detail.get(i);
//                for (int j = 0; j < i; j++) {
//                    PosTransactionDistributionDetail d2 = (PosTransactionDistributionDetail) detail.get(j);
//                    if (d2.getDistributionDetailItemId().equals(d1.getDistributionDetailItemId())) {
//                        d2.setDistributionDetailQuantity(d2.getDistributionDetailQuantity()+ d1.getDistributionDetailQuantity());
//                        detail.remove(i);
//                        break;
//                    }
//                }
//            }
        }

        @Override
        public void beforeUpdate(Object data, List list, List listDelete) {
            PosTransactionDistribution distribution = (PosTransactionDistribution) data;
            distribution.setDistributionProgress("1");
            distribution.setDistributionRejectReason(Dictionary.getValue(page, "Revision") + ": " + distribution.getDistributionRejectReason());
        }
    }

    public String generate() {
        String unitCode = (getCurrentUnit()).getUnitCode();
        Calendar cal = Calendar.getInstance();
        String year = "" + cal.get(Calendar.YEAR);
        String month = Utility.intToRoman(cal.get(Calendar.MONTH) + 1);
        try {
            PosTransactionDistribution distribution = (PosTransactionDistribution) getEntityManager().createQuery("SELECT t FROM PosTransactionDistribution t WHERE t.distributionNumber LIKE '%/" + unitCode + "/DIS/%/" + year + "' ORDER BY t.distributionTimestamp DESC").setHint(Persistence.REFRESH_HINT, true).setFirstResult(0).setMaxResults(1).getSingleResult();
            return Utility.lpad(Integer.parseInt(distribution.getDistributionNumber().substring(0, 4)) + 1, 4, "0") + "/" + unitCode + "/DIS/" + month + "/" + year;
        } catch (Exception e) {
        }
        return "0001/" + unitCode + "/DIS/" + month + "/" + year;
    }

    @Override
    public void beforeExport() {
        getExportParams().put("title", Dictionary.getValue(this, "Distribution"));
    }

    @Override
    public void beforeExportMulti() {
        beforeExport();
    }
}
